/**
 * 已办组件(基于ECP3.0前端).
 * 
 * @author xuetianfu
 * @since 2016-06-24
 */
define([ 'jquery','ecp.service', 'ecp.utils', 'ecp.utils.i18n','wfUtils','auditOption','batchAudit','ecp.pagemessage','ecp.component.dialog','qzz.paged','jquery.scrollLoading','attatchment'],
    function(jq,ecpService, ecpUtils,i18n,wfUtils,auditOption,bAudit,message,$dialog) {
    var USER_ID = ecpService.DataContextUtil.getUserId();
    var USER_DISPLAY_NAME = ecpService.DataContextUtil.getUserDisplayName();
    
        var TASK_CONST = {
            CATEGORY : {
                UNTREATED : "1",
                EXECUTED : "2"
            },
            TASK_STATUS : {
                NORMAL : "0",
                PROCESSING : "1",
                SUCCESS : "2",
                ERROR : "3",
                INVALID : "4",
                PAUSE : "5",
                RESUME : "6",
                HASTEN : "7",
                FINISH:"8"
            },
            ORDER_FIELDS:[ "taskcreatetime","busno","seq","pruserid","typeid","taskprocessorid","taskdealtime" ]
        };
        

        /**
        *待办按钮顺序：1.【继续填单】|2.【进入审批】|3.【直接审批】|4.【查看审批意见】|5.【回退】|6.【作废】
		*已办按钮顺序：1.【加急】|2.【撤回】|3.【查看审批意见】
		*已和小攀确定过【直接审批】目前只在极速审批格式使用。
		*【继续填单】是首节点保存的待办记录显示，其它流转中的流程都显示【进入审批】，所以待办按钮的1、2、3只会显示其中一个。
        */
        //待办 "viewAduit"因流程按钮名称写错,将错就错
        var untreatedBtnList = ["fill","passAndAudit","audit","viewAduit","getback","cancel"];
        
        //已办
        var executeBtnList = ["hasten","callback","viewAduit"];
        
        /**
         * 分页控件参数.
         */
        var PAGE_OPTIONS = {
            pageSize : 10
        };

        // 参数
        var CONF = {};
        
        /**
         * 前端上下文.
         */
        CONF.context = ecpService.DataContextUtil.getEcpDataContext();

        /**
         * 接口类.
         */
        var BEAN_ID = "com.ygsoft.ecp.core.web.taskcenter.context.IQueryContext";

        /**
         * 后端服务对象.
         */
        var remoteService = ecpService.RemoteService;

        /**
         * 动态加载插件,并缓存JS对象.
         */
        var EXT_POINT_LIST_CACHE = {};
 
        /**
         * 任务列表缓存.
         */
        var TASK_LIST_CACHE = {};

        /**
         * 任务按钮配置缓存.
         */
        var TASK_BTN_CACHE = [];
        
        /**
         * 当前页任务VO数组.
         */
        var TASK_VO_LIST = [];

        /**
         * 加载扩展点.
         */
        function requireBatch(jsUrls, callback) {
            if (!jsUrls || !jsUrls.length) {
                return;
            }
            var split = ",";
            var arrStr = "";
            var jsList = "";
            $(jsUrls).each(function(i, n) {
                jsList += "'" + n + "'" + split;
                arrStr += "js" + i + split;
            });
            jsList = jsList.substr(0, jsList.length - 1);
            arrStr = arrStr.substr(0, arrStr.length - 1);

            var str = "require([" + jsList + "], function(" + arrStr + "){\n";
            str += " var varList = [" + arrStr + "];\n";
            str += "  if(callback) callback.call(null,varList);\n"
            str += "});"
            eval(str);
        }
        
        /**
        *扩展点模块缓存.
        */
        var EXT_POINT_MK_CACHE={};
        
        /**
         * 加载任务扩展点.
         */
        function loadTaskExtList() {
            remoteService.doPostAsync(BEAN_ID, "getTaskExtList",[ CONF.context ], function(result, xhr) {
                var extUrlList = result.data;
                if (!extUrlList || !extUrlList.length) {
                    return;
                }
                var jsList = [];
                var typeList = [];
                var mcList = [];
                $.each(extUrlList, function(i, ext) {
                    jsList[i] = ext.jsUrl;
                    typeList[i] = ext.type;
                    mcList[i]=ext.mkjc;
                    var newBtnSettings = $.parseJSON(ext.btnSettings);
                    //没有按钮,只定义扩展
                    if(newBtnSettings){
                        var oldBtnSettings = TASK_BTN_CACHE[ext.type];
                        if (oldBtnSettings) {
                            $.each(oldBtnSettings, function(i) {
                                newBtnSettings.push(oldBtnSettings[i]);
                            });
                            TASK_BTN_CACHE[ext.type] = newBtnSettings;
                        } else {
                            TASK_BTN_CACHE[ext.type] = newBtnSettings;
                        }
                    }
                });
                initExtPointCacheByMK(jsList,typeList,mcList);
            });
        }
        
        /**
        *根据初始化模块缓存对象.
        *@param jsList jsUrl数组
        *@param typeList 类型数组
        *@param mcList 模块数组
        */
        function initExtPointCacheByMK(jsList,typeList,mcList){
        	requireBatch(jsList, function(extProxyList) {
                $.each(extProxyList, function(i, extProxy) {
                    var type = typeList[i];
                    if(jsList[i]==GLOBAL_WF_URL){
                    	EXT_POINT_LIST_CACHE[type+'_WF'] = extProxy;
                    }else if(jsList[i]==GLOBAL_DJ_URL){
                    	EXT_POINT_LIST_CACHE[type+'_DJ'] = extProxy;
                    }else{
                        if(EXT_POINT_LIST_CACHE[type]){
                           EXT_POINT_LIST_CACHE[type + (Math.random()*100+1)] = extProxy;
                        }else{
                        	EXT_POINT_LIST_CACHE[type] = extProxy;
                        }
                    }
                    var obj = {};
                    obj.oldType=typeList[i];
                    obj.type=type;
                    obj.mkjc=mcList[i];
                    obj.jsUrl = jsList[i];
                    obj.extObj = extProxy;
                    EXT_POINT_MK_CACHE[jsList[i]]=obj;
                    if(obj.jsUrl==GLOBAL_WF_URL){
                        var funcObj = getFuncObj(obj.oldType,'initedCallBack');
                        if(funcObj){
                          	funcObj($("#tab_1",COMPONENT_CONTAINER),UNTREATED_TASK_LIST_CACHE,{"isUntreated":true});
                        }
                    }
                    invokeLazyload(true);
                })
            });
        }


        /**
         * 当前列表内容填充区ID.
         */
        var CURRENT_QUERY_METHOD;
        var CURRENT_QUERY_PARAMS;
        
        /**
         * 设置当前列表内容填充区ID.
         *@param  queryMethod 查询方法
         *@param  queryParams 查询参数
         */
        function setCurQuery(queryMethod, queryParams) {
            CURRENT_QUERY_METHOD = queryMethod;
            CURRENT_QUERY_PARAMS = queryParams;
        }
            
        /**
		 * 当前是否待办箱.
		 */
		function isUnTreated() {
			return $("ul.nav-tabs > li",COMPONENT_CONTAINER).index($("ul.nav-tabs > li.active",COMPONENT_CONTAINER)) == 0;
		}

        /**
         * 刷新页面.
         */
        function refreshPage() {
            if(isUnTreated()){
            	refreshUnTreatedTaskList();
            }else{
           		refreshExecutedTaskList();
            }
        }
        
        /**
         * 重新执行最新的查询.
         */
        function redoQuery() {
            if (CURRENT_QUERY_METHOD && CURRENT_QUERY_PARAMS) {
                CURRENT_QUERY_METHOD.apply(this, CURRENT_QUERY_PARAMS);
            }
        }
        
        var UNTREATED_PARAMS;
        var EXECUTED_PARAMS;
        
        /*
        *设置待办/已办查询参数.
        */
        function setInitParams(untreatedParams,executedParams,contentContainer){
        	UNTREATED_PARAMS=untreatedParams;
        	EXECUTED_PARAMS=executedParams;
        	COMPONENT_CONTAINER=contentContainer;
        }
        
        var COMPONENT_CONTAINER;
        
        /*
        *刷新已办列表.
        */
        function refreshExecutedTaskList(){
			 loadExecutedTaskList(getQueryParams(true),EXECUTED_PARAMS[1],EXECUTED_PARAMS[2],EXECUTED_PARAMS[3],EXECUTED_PARAMS[4]);
        }
        
        /*
        *刷新待办列表.
        */
        function refreshUnTreatedTaskList(){
			loadUnTreatedTaskList(getQueryParams(false),UNTREATED_PARAMS[1],UNTREATED_PARAMS[2],UNTREATED_PARAMS[3],UNTREATED_PARAMS[4]);
        }
        
        /**
        *刷新整个页面,软刷新方式.
        */
        function refreshAll(){
           refreshUnTreatedTaskList();
           refreshExecutedTaskList();
        }
        
        /**
         * 移除显示任务项.
         *@param btnObj 任务项对应的按钮对象
         */
        function removeTaskItem(btnObj) {
            if (btnObj) {
                btnObj.closest("li[taskid]").remove();
            }
        }
        
        /**
         * 打开详细页面.
         *@param container 任务列表容器
         */
        function activeTaskClick(container) {
            $(".djInfor",container.parent()).on('click', function(e){
                var currentTarget = $(e.target);
                if(currentTarget.hasClass("link_attachment")){
                    var attachList = $(this).closest("li[taskid]").data();
			    	var el = $(this).closest("div.col-md-6").siblings("div.col-md-4").find("div[tag='wfAttachment']");
				    viewAttachment(attachList,el);
                }else{
                    var taskType = $(this).attr("taskType");
                    var mkjc = $(this).attr("mkjc");
                    var taskVO = TASK_VO_LIST[$(this).closest("li").attr("taskid")];
                    // 必须实现查看详细页面方法
                    var funcObj;
                    if(!mkjc){
                    	funcObj = getFuncObj(taskType, "openIt");
                    }else{
                    	funcObj = getMkFuncObj(mkjc,taskType, "openIt");
                    }
                    if (funcObj) {
                        updateTaskRead(taskVO,funcObj);
                    }
                }
            });
        }
        
        /**
        *具体模块的JS方法.
        */
        function getMkFuncObj(mkjc,taskType,method){
           var funcObj;
           $.each(EXT_POINT_MK_CACHE,function(i){
                if(EXT_POINT_MK_CACHE[i].mkjc==mkjc){
                  if(EXT_POINT_MK_CACHE[i].extObj[method]){
                   		funcObj=EXT_POINT_MK_CACHE[i].extObj[method];
                   		return false;
                   }
                }
           });
           //查找不到再从其它扩展点找
			if(!funcObj){
		    	$.each(EXT_POINT_LIST_CACHE, function(typeName) {
					if (typeName.startsWith(taskType)) {
						var func = EXT_POINT_LIST_CACHE[typeName][method];
						if (func) {
							funcObj = func;
							return false;
						}
					}
           		 });
       		 }
           return funcObj;
        }
        
        /**
        *更新任务已阅读状态.
        *@param taskVO 任务VO对象
        *@parm funcObj 已阅读调用方法JS对象
        */
        function updateTaskRead(taskVO,funcObj){
            if(!taskVO)return;
            if(taskVO.isRead==0){
                remoteService.doPostAsync(BEAN_ID, 'finishRead', [taskVO.taskId], function(resp) {
                    if (resp.isSuccess()) {
                        funcObj(taskVO);
                    }
                    if (resp.isError()) {
                        ecpUtils.notify(resp.data);
                    }
                });
            }else{
               funcObj(taskVO);
            }
        }

        /**
         * 加载待办任务列表.
         *@param queryFields 查询字段
         *@param orderByFields 排序字段
         *@param contentArea 任务列表区域
         *@param pageArea 翻页控件区域
         *@param callBak 回调函数
         */
        function loadUnTreatedTaskList(queryFields, orderByFields,contentArea, pageArea, callBak) {
            getTaskList(true,'getUntreatedTaskSizeByCondition', queryFields,orderByFields, 'getUntreatedTaskList', contentArea,pageArea, callBak);
            setCurQuery(loadUnTreatedTaskList, [ queryFields, orderByFields, contentArea, pageArea ]);
        }
        
        /**
         * 加载已办任务列表.
         *@param queryFields 查询字段
         *@param orderByFields 排序字段
         *@param contentArea 任务列表区域
         *@param pageArea 翻页控件区域
         *@param callBak 回调函数
         */
        function loadExecutedTaskList(queryFields, orderByFields,contentArea, pageArea, callBak) {
            getTaskList(false,'getExecutedTaskSizeByCondition', queryFields,orderByFields, 'getExecutedTaskList', contentArea,pageArea, callBak);
            setCurQuery(loadExecutedTaskList, [ queryFields, orderByFields, contentArea, pageArea ]);
        }


        /**
         * 获取查询结果总条数.
         *
         *@param resSizeArea
         *            结果总条数
         *@return 查询结果总条数
         */
        function getQueryResSize(resSizeArea) {
            return CURRENT_UNTREATED_QUERY_RES_SIZE;
        }
        
        var QZZ_PAGE_CONTAINER={};
        
        /*
        *待办缓存.
        */
        var UNTREATED_TASK_LIST_CACHE;
        
        /*
        *忆办缓存.
        */
        var EXECUTED_TASK_LIST_CACHE;
        
        /*
        *最新查询的待办总数.
        */
        var CURRENT_UNTREATED_QUERY_RES_SIZE;
        
        /**
         * 加载任务列表.
         *@param isUntreated 是否待办
         *@param queryCountAction 查询总数方法名称
         *@param queryFields 查询字段
         *@param orderByFields 排序字段
         *@param queryAction 查询方法名称
         *@param resAreaObj 查询结果填充区域
         *@param pageAreaObj 分页控件填充区域
         *@param callBak 回调函数
         */
        function getTaskList(isUntreated,queryCountAction, queryFields, orderByFields,
                              queryAction, resAreaObj, pageAreaObj, callBak) {
            getServerNowTime();
            if(resAreaObj){
	            resAreaObj.siblings(".wfloading").removeClass("display-hide");
	            resAreaObj.siblings("li.taskItem").remove();
	            resAreaObj.find(".freshPage").attr("disabled","disabled");
            }
            //取得查询总数
            remoteService.doPostAsync(BEAN_ID, queryCountAction,
                [ queryFields ], function(resp) {
                    if (resp.isSuccess()) {
                        if(resp.data>0){
                       			processBatchAuditTask(resAreaObj);
                        }
                        updatePagination(resAreaObj,pageAreaObj,resp.data,isUntreated,queryAction,queryFields,orderByFields);
                        if(isUntreated){
                           CURRENT_UNTREATED_QUERY_RES_SIZE = resp.data;
                        }
                        if (callBak) {
                            callBak();
                        }
                        var qzzPageObj = QZZ_PAGE_CONTAINER[pageAreaObj.attr("id")];
                        var pageSize = qzzPageObj.getPageSize();
                        //查询列表,注意参数的顺序--后端API必须与前端顺序一致
                        var pageIdx = 1;
                        if(!isQueryTriggerBySearch){
                        //原查询维度是第3页,切换维度后,还应该是第3页,这是需求决定的
                              if(!queryChanged){
		                          pageIdx = qzzPageObj.getPageIndex();
                              }
                        }
                        if(pageIdx==1){
	                          qzzPageObj.firstPage(); 
                        }
                        queryTaskList(isUntreated,queryAction,[pageSize, pageIdx, queryFields,orderByFields ],resAreaObj);
                    }
                    if (resp.isError()) {
                        ecpUtils.notify(resp.data);
                        resAreaObj.siblings(".wfloading").addClass("display-hide");
                        resAreaObj.find(".freshPage").removeAttr("disabled");
                    }
                });
        }
        
        /*
        *查询数据集.
        *@param isUntreated 是否待办
        *@param action 执行方法名称
        *@param params 参数
        *@param resAreaObj 输出区域对象
        *@return 数据集
        */
        function queryTaskList(isUntreated,action,params,resAreaObj){
        	remoteService.doPostAsync(BEAN_ID, action, params, function(resp) {
                if (resp.isSuccess()) {
                    resAreaObj.siblings(".wfloading").addClass("display-hide");
                    if(resp.data&&resp.data.length==0){
                         resAreaObj.siblings("li.taskItem").remove();
                    }else{
                    	TASK_LIST_CACHE = resp.data;
                    	if(isUntreated){
                          	UNTREATED_TASK_LIST_CACHE = resp.data;
                        }else{
                          	EXECUTED_TASK_LIST_CACHE = resp.data;
                        }
                    	dataProcess(isUntreated,resAreaObj, resp.data);
                    }
                	var len = resAreaObj.siblings("li.taskItem").find("li.fixTask:visible").length;
                	if(len==0){
	                    resAreaObj.find(".freshPage").removeAttr("disabled");
                	}
                }
                if (resp.isError()) {
                    ecpUtils.notify(resp.data);
                    resAreaObj.siblings(".wfloading").addClass("display-hide");
                    resAreaObj.find(".freshPage").removeAttr("disabled");
                }
             });
        }
        
        /**
        *更新翻页控件.
        *@param resAreaObj 查询结果填充区域
        *@param pageAreaObj 翻页控件容器
        *@param totalCount 翻页控件显示总条数
        *@param isUntreated 是否待办
        *@param queryAction 查询方法名称
        *@param queryFields 查询字段
        *@param orderByFields 排序字段
        */
        function updatePagination(resAreaObj,pageAreaObj,totalCount,isUntreated,queryAction,queryFields,orderByFields){
  				var paginationObj = QZZ_PAGE_CONTAINER[pageAreaObj.attr("id")];
            	if(!paginationObj){
                    var paged = pageAreaObj.qzzpaged({"totalCount":totalCount,'pageSize' : PAGE_OPTIONS.pageSize});
                    QZZ_PAGE_CONTAINER[pageAreaObj.attr("id")] = paged;
	                QZZ_PAGE_CONTAINER[pageAreaObj.attr("id")].bind("onPageChanged",
	                function(pc, ps, pi) {
	                    pageChange(isUntreated,queryAction, null, orderByFields,resAreaObj, ps, pi);
	                });
                }else{
                    paginationObj.setTotalCount(totalCount,false);
                }
        }
        
        /**
        *获取能够批量审批的任务列表.
        *@param container 任务列表容器
        *@return 能够批量审批的任务列表
        */
        function processBatchAuditTask(container){
        		var dc = ecpService.DataContextUtil;
                //批量审批权限判断
				var params = [
						dc.getEcpDataContext(),
						"authority.subfunc",
						{
							"jcls":"com.ygsoft.ecp.component.permission.service.model.fw.GeneralVisitConditionVO",
							"principalId":dc.getLoginOrgId(),
							"principalType":"all",
							"dwdm":dc.getLoginOrgId(),
							"yhdm":dc.getUserId(),
							"pageId":"reimburse.todoList"   
						}
				]
				var beanId = "com.ygsoft.ecp.component.permission.service.fw.context.IPermissionVisitContext";
				remoteService.doPostAsync(beanId,"getPmsnVisitList",params,function(resp){
					if (resp.isSuccess()) {
						var resVo = resp.data.generalResourceCtrlVOs[0]; 
						if(resVo && resVo.resourceId){
							//权限不足
							$("#batchReject",container).hide();
						}else{
							//判断是否含有批量审批任务
				            var userId = dc.getUserId();
				            remoteService.doPostAsync(BEAN_ID, 'hasCanBatchAuditTask',[ userId ], function(resp) {
				                if (resp.isSuccess()) {
				                	if(resp.data&&resp.data=='true'){
				                		//构造批量审批弹出窗口
				                		$("#batchReject",container).show();
				                   	 	loadBatchAuditData(container);
				                    }else{
				                    	//没有批量审批单据
				                    	$("#batchReject",container).hide();
				                    }
				                }
				                if (resp.isError()) {
				                        ecpUtils.notify(resp.data);
				                        $("#batchReject",container).hide();
				                }
				            });
							
						}
					}else{
						ecpUtils.notify(resp.data);
					}
				});
        }
        
        /**
        *加载批量审批数据.
        *@param container 任务列表容器
        */
        function loadBatchAuditData(container){
        	//构造批量审批弹出窗口
        	$('[data-target="#hdsplbModal"]',container).off("click").on("click",function(){
            	var userId = ecpService.DataContextUtil.getUserId();
	            remoteService.doPostAsync(BEAN_ID, 'getCanBatchAuditTaskList',[ userId ], function(resp) {
	                if (resp.isSuccess()) {
	                    if(resp.data && resp.data.length>0){
							renderCheckAuditGrid(container,resp.data);
			            }
	                }
	                if (resp.isError()) {
	                    ecpUtils.notify(resp.data);
	                }
	            });
            });
        }

        /**
         * 填充总计区域.
         *
         * @param areaObj
         *            总计区域
         * @param count
         *            总计
         */
        function fillCountArea(areaObj, count) {
            if (areaObj && count > 0) {
                areaObj.html(count);
            }
        }

        /**
         * 翻页事件.
         *@param isUntreated 是否待办
         * @param action
         *            执行后端方法名称
         * @param sumAreaObj
         *            总数放置区
         * @param queryFields
         *            查询字段
         * @param orderByFields
         *            排序字段
         * @param resAreaObj
         *            结果放置区
         * @param pageSize
         *            每页记录数
         * @param pageNo
         *            页码序号
         */
        function pageChange(isUntreated,action, sumAreaObj, orderByFields,resAreaObj, pageSize, pageNo) {
        	//如果查询维度变化了,必须重新输入查询条件
        	var params = getQueryParams(!isUntreated);
            remoteService.doPostAsync(BEAN_ID, action, [ pageSize, pageNo,params, orderByFields ], function(resp) {
                if (resp.isSuccess()) {
                	if(isUntreated){
                    	UNTREATED_TASK_LIST_CACHE = resp.data;
                    }else{
                        EXECUTED_TASK_LIST_CACHE = resp.data;
                    }
                    dataProcess(isUntreated,resAreaObj, resp.data);
                    fillCountArea(sumAreaObj, resp.data.length);
                }
                if (resp.isError()) {
                    ecpUtils.notify(resp.data);
                }
            });
        }

       var SERVER_NOW_TIME;
       var now;  //当前日期
       var nowDayOfWeek;//今天本周的第几天
       var nowDay;//当前日
       var nowMonth;//当前月
       var nowYear;//当前年
       
        /**
         * 获取服务器当前时间.
         *
         * @return 服务器当前时间
         */
        function getServerNowTime() {
            remoteService.doPostAsync(BEAN_ID, "getServerNowTime", [],function(resp) {
                if (resp.isSuccess()) {
                    SERVER_NOW_TIME = resp.data;//当前日期
                    var nowTimeStr = ecpUtils.strToDate(SERVER_NOW_TIME, true, true,true);
					//1148248 解决IE下"2014-01-01 10:20:10"不能new Date转换问题
					var ecpDateStr = ecpUtils.parseEcpDate(nowTimeStr);
					var nowTimeDate = ecpUtils.jsonStrToDate(ecpDateStr);
					if(!nowTimeDate || nowTimeDate.length === 0){
						nowTimeDate = new Date(nowTimeDate);
					}
                    nowDayOfWeek = nowTimeDate.getDay();//今天本周的第几天
                    nowDay = nowTimeDate.getDate();//当前日
                    nowMonth = nowTimeDate.getMonth();//当前月
                    nowYear = nowTimeDate.getYear();//当前年
                    nowYear += (nowYear < 2000) ? 1900 : 0;//防止用户将电脑时间调整错误导致问题
                }
                if (resp.isError()) {
                    ecpUtils.notify(resp.data);
                }
            });
        }

        /**
         * 数据处理.
         *@param isUntreated 是否待办
         *@param container
         *            数据放置区
         *@param data
         *            数据集
         */
        function dataProcess(isUntreated,container, data) {
            var selectedBtn = container.parent().find(".topBar>button.active");
            var idx = container.parent().find(".topBar>button").index(selectedBtn);
            //按到达时间排序
            if(idx==0){
	            outputHtml_groupby_creattime(isUntreated,container,data);
            }else if(idx==1||idx==2){
               outputHtml_groupby_busNoOrPrice(isUntreated,container,data);
            }else if(idx==3){
               outputHtml_groupby_pruserid(isUntreated,container,data);
            }else if(idx==4){
               outputHtml_groupby_busType(isUntreated,container,data);
            }
            if(isUntreated){
               var sum=0;
               $.each(data,function(i){
                   if(data[i].subtotal&&data[i].subtotal>0){
                     sum=sum*1+data[i].subtotal*1;
                   }
               });
               //1151102
               var oldCount= CURRENT_UNTREATED_QUERY_RES_SIZE;
               if(oldCount!=countLimitStr){
                    var newCount = oldCount*1+sum;
               		setTodoCount(newCount);
	               //通知门户待办刷新总数
	               if(window.top.pageMessage){
	 				   window.top.pageMessage.send("TODO_NUMBER_REFRESH", {count:newCount});
		           }
	            }
            }
            addFuncs(container,isUntreated);
        }
       
       /**
        *
        *输出html(根据业务编号或金额分组排序).
        *@param isUntreated 是否待办
        *@param container 输出html容器
        *@param data 任务数据数组
        */
        function outputHtml_groupby_pruserid(isUntreated,container,data){
        		var group = {};
           		var userName;
           		var isFixTask = false;
                $.each(data,function(i, obj) {
                	isFixTask = obj.detail&&obj.detail.indexOf("fixTask")!=-1;
                    userName = (obj.yhxsmc?obj.yhxsmc:(isFixTask?"999999999":(obj.pruserId<=0?USER_DISPLAY_NAME:'nm')));
                    if (!group[userName]) {
                      group[userName]=[];
                    }
                    group[userName].push(obj);
                });
                var outputHtml = getOutputHtml(isUntreated,group);
                //去掉分页控件,加载中效果
                container.siblings().not(".winStyle,.wfloading").remove();
                //将html插入加载效果后面
                $(outputHtml).insertBefore(container.siblings(".wfloading"));
        }
        
       /**
        *
        *输出html(根据业务编号或金额分组排序).
        *@param isUntreated 是否待办
        *@param container 输出html容器
        *@param data 任务数据数组
        */
        function outputHtml_groupby_busType(isUntreated,container,data){
        	   var group = {};
               $.each(data,function(i, obj) {
                    var taskName = obj.taskName;
                    if(taskName){
	                    if (!group[taskName]) {
	                      group[taskName]=[];
	                    }
                    	group[taskName].push(obj);
                    }else{
                       	if(!group['nm']){
                    		group['nm']=[];
                        }
                        group['nm'].push(obj);
                    }
                });
                var outputHtml = getOutputHtml(isUntreated,group);
                //去掉分页控件,加载中效果
                container.siblings().not(".winStyle,.wfloading").remove();
                //将html插入加载效果后面
                $(outputHtml).insertBefore(container.siblings(".wfloading"));
        }
        
        /**
        *
        *输出html(根据业务编号或金额分组排序).
        *@param isUntreated 是否待办
        *@param container 输出html容器
        *@param data 任务数据数组
        */
        function outputHtml_groupby_busNoOrPrice(isUntreated,container,data){
        	var html = [];
               html.push('<li class="taskItem"><ul class="listGroupContent">');
               $.each(data,function(i, obj) {
                    if(!obj.html){
	                  	var json=parseTaskDetail(html,obj);
		                if (json && json.btnInfo) {
		                    var newBtnHtml=rebuildBtnHtmlWithSort(isUntreated,json.btnInfo,obj);
		                    html.push(getTaskHTML(obj,json.userInfo,json.bizInfo,json.seqInfo,newBtnHtml));
		                }
	                }else{
	                     html.push(obj.html);
	                }
                });
               html.push('</ul></li>');
               container.siblings().not(".winStyle,.wfloading").remove();
               $(html.join('')).insertBefore(container.siblings(".wfloading"));
        }
        
        /**
        *获取最后输出的html.
        *@param isUntreated 是否待办
        *@param group 数据
        *@return  最后输出的html
        */
        function getOutputHtml(isUntreated,group){
    		var html = [];
            html.push("<li class='taskItem'>");
            var totalVal;
            var captionVal;
            $.each(group, function(i, item) {
                //特殊待办分组显示为0条
                var count =0;
                var isFixTaskGroup = false;
                $.each(item,function(i,e){
                   if(item[i].html&&item[i].html!=''){
                     count++;
                   }
                   if(item[i].detail&&item[i].detail.indexOf("fixTask")!=-1){
                      isFixTaskGroup=true;
                   }
                });
                totalVal = count==item.length?0:item.length;
                
                //当前是固定待办分组则不显示分组栏
                if(!isFixTaskGroup){
					html.push("<ul class=\"listGroupTitle\">");
					html.push("<li><a class=\"lgt_collapse open\"><i class=\"fa fa-caret-up\"></i></a></li>");
					captionVal = (i=='nm'?'':i); 
					html.push("<li><i></i><span class=\"caption\">"+captionVal+"</span></li><li><span>"+i18n.wfTodoAndDone.sum+ totalVal +"  "+i18n.wfTodoAndDone.totalrow+"</span></li>"); 
					html.push("</ul>");
				}
				
                var tmpHtml = [];
				tmpHtml.push("<ul class=\"listGroupContent\" id=\"listContentchk\">");
                $.each(item, function(j, obj) {
                    if(!obj.html){
	                  	var json=parseTaskDetail(tmpHtml,obj);
		                if (json && json.btnInfo) {
		                    var newBtnHtml=rebuildBtnHtmlWithSort(isUntreated,json.btnInfo,obj);
		                    tmpHtml.push(getTaskHTML(obj, json.userInfo,json.bizInfo, json.seqInfo, newBtnHtml));
		                }
	                }else{
	                    tmpHtml.push(obj.html);
	                }
                });
                tmpHtml.push("</ul>");
                html.push(tmpHtml.join(''));
            });
            html.push("</li>");
            return html.join('');
        }
        
        /*
        *
        *@param element html元素
        *@return 元素属性对象
        */
        function getAttribute(element,data){
            var startPos = element.indexOf("<button");
            var endPos = element.indexOf("</button>");
            var btn  = element.substring(startPos,endPos+"</button>".length);
            var btnHtml_ = element.substring(element.indexOf("</button>")+"</button>".length);
            var btnObj = {};
            btnObj['taskType'] = getBetweenStr(btn,"taskType=\"","\"");
            btnObj['name'] = getBetweenStr(btn,"name=\"","\"");
            btnObj['class'] = getBetweenStr(btn,"class=\"","\"");
            if(btnObj['taskType']!=''){
            	data.push(btnObj);
            }
            if(btnHtml_.indexOf("<button")!=-1){
                getAttribute(btnHtml_,data);
            }
        }
        
        /**
        *获取字符串中间字符.
        *@param str 字符串
        *@param startStr 开始字符串
        *@param endStr 结束字符串
        *@return 返回字符串中间字符
        */
        function getBetweenStr(str,startStr,endStr){
           var str_ = str.substring(str.indexOf(startStr)+startStr.length);
           return str_.substring(0,str_.indexOf(endStr));
        }
        
        //待办任务最大显示99,大于99显示为"99+".
        var countLimitStr = "99+";
        
        /**
        *设置待办总数显示效果.
        */
        function setTodoCount(count){
            if(count>0){
	            if(count>99){
	                var oldCount = $("#sumOfUnexecuted",COMPONENT_CONTAINER).html();
	                if(oldCount!=countLimitStr){
	        			$("#sumOfUnexecuted",COMPONENT_CONTAINER).html(countLimitStr);
	        		}
	        	}else{
	        		$("#sumOfUnexecuted",COMPONENT_CONTAINER).html(count);
	        	}
	        	$("#sumOfUnexecuted",COMPONENT_CONTAINER).html(count).addClass('bg-danger');
        	}else{
        		$("#sumOfUnexecuted",COMPONENT_CONTAINER).html('').removeClass('bg-danger');
        	}
        }
        
       /**
       *
       *数据分组.
       */
        function getDay2GroupStr(groupData,time,taskItem){
             //获得上周的开始日期
             var upWeekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek+1-7);
        	 //获得本周的开始日期
             var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek+1);
             //今天
             var currentDate = new Date(nowYear, nowMonth, nowDay);
             //昨天
             var yesterdayDate = new Date(nowYear, nowMonth, nowDay - 1);
             
             var key = 0;
             //更早
             if(time.getTime()<upWeekStartDate.getTime()){
             		key=-100;
             //上周
             }else if((time.getTime()>=upWeekStartDate.getTime())&&(time.getTime()<weekStartDate.getTime())){
             	    key=-99;
             //本周
             }else if(time.getTime()>=weekStartDate.getTime()){
             	//今天
             	if(time.getTime()>=currentDate.getTime()){
             	    key=-98;
             	//昨天
             	}else if(time.getTime()>=yesterdayDate.getTime()){
             	   key=-97;
             	//当前周的其它星期几
             	}else{
             	   key = number2WeekDay(time.getDay());
             	}
             }
             if (!groupData[key]) {
	            groupData[key] = [];
	         }
	         groupData[key].push(taskItem);
        }
        
        /**
        *
        *输出html(根据创建时间分组).
        *@param isUntreated 是否待办
        *@param container 输出html容器
        *@param data 任务数据数组
        */
        function outputHtml_groupby_creattime(isUntreated,container,data){
	            var dataContainer = {};
	            // 数据归类
	            $.each(data, function(idx, obj) {
	                var createTime = ecpUtils.jsonStrToDate(obj.taskCreateTime);
					if(!createTime || createTime.length === 0){
						createTime = new Date(createTime);
					}
	                getDay2GroupStr(dataContainer,createTime,obj);
	            });
	            // 数据输出
	            outputHTML(isUntreated,container,dataContainer);
        }
        
        /**
        *待任务项加载后激活功能.
        *@param container 数据放置区
        *@param isUntreated 是否待办
        *            
        */
        function addFuncs(container,isUntreated){
            //button内容填充
            drawTaskBtn();
            //增加流程修复快捷键
            addRepairHotKey();
            //增加流程修复按钮
            addRepairBtn();
            //激活任务按钮
            activeTaskBtn(container);
            //激活点击查看任务详细功能
            activeTaskClick(container);
            //个人头像渲染
            renderUserphoto(container);
            //个人头像鼠标停留显示详细功能
            showUserDetail(container);
            //增加附件个数
            showAttachment(container);
            if(isQueryTriggerBySearch){
            	openWhenOnlyOne(container);
            	//搜索时应隐藏固定待办
            	var firstTaskItem = $("li.topBar",COMPONENT_CONTAINER).siblings("li.taskItem");
	        	var isExists = firstTaskItem && (firstTaskItem.find("ul.dynamic").length >  0);
	        	if(isExists){
		        	firstTaskItem.first().hide();
	        	}
            }
            renderPrice();
            addZNTXFunc(container);
            addCss2LastTaskItem(container);
            invokeLazyload(isUntreated);
            //隐藏按钮前的图标
            $(".listGroupContent .djActions button i", COMPONENT_CONTAINER).hide();
			$("span.djType",COMPONENT_CONTAINER).each(function(){$(this).attr("title",$(this).text().trim())});
			$("span.djNumber",COMPONENT_CONTAINER).each(function(){$(this).attr("title",$(this).text().trim())});
			$("p.processor",COMPONENT_CONTAINER).each(function(){$(this).attr("title",$(this).text().trim())});
			
			$("span.djType",COMPONENT_CONTAINER).each(function(){
			    if(!$(this).parent().is("b")){
			    	$(this).prop('outerHTML','<b class="left">'+$(this).prop('outerHTML')+'</b>');
			    }
			});
			
			$("span.djNumber",COMPONENT_CONTAINER).each(function(){
			    if(!$(this).parent().is("b")){
			    	$(this).prop('outerHTML','<b class="right">'+$(this).prop('outerHTML')+'</b>');
			    }
			});
        }
        
         /*
         *修复模式.
         */
         var debugIsOpen = false;
         
        /**
        *debug模式,增加恢复按钮.
        */
        function addRepairBtn(){
            if(debugIsOpen){
	        	$("li[taskid]",COMPONENT_CONTAINER).find("div.djActions").each(function(){
	        	   	$(this).append('<button  name="repair" taskType="system" class="btn btn-default"><i class="icon_sm icon_shenpi"></i>'+i18n.wfTodoAndDone.repair+'</button>');
	        	});
        	}
        }
        
        /*
        *增加修复快捷捷CTRL+K.
        */
        function addRepairHotKey(){
			var HotKeyHandler={ 
				currentMainKey:null, 
				currentValueKey:null, 
				open:function(){ 
					HotKeyHandler.Register(0,"K",function(){
					    if(debugIsOpen){
					       debugIsOpen = false;
					    }else{
					    	debugIsOpen = true;
					    }
					}); 
				},
			
				Register:function(tag,value,func){ 
					var MainKey=""; 
					switch(tag){ 
						case 0: 
						MainKey=17; //Ctrl 
						break; 
						case 1: 
						MainKey=16; //Shift 
						break; 
						case 2: 
						MainKey="18"; //Alt 
						break; 
					} 
					document.onkeyup=function(e){ 
						HotKeyHandler.currentMainKey=null; 
					} 
					document.onkeydown=function(event){ 
					//获取键值
					var keyCode= event.keyCode ; 
					var keyValue = String.fromCharCode(event.keyCode); 
					if(HotKeyHandler.currentMainKey!=null){ 
						if(keyValue==value){ 
							HotKeyHandler.currentMainKey=null; 
							if(func!=null)func(); 
						} 
					} 
					if(keyCode==MainKey) 
						HotKeyHandler.currentMainKey=keyCode; 
					} 
				} 
			} 
			HotKeyHandler.open();
		}
        
        /**
        *渲染价格,加入千分位.
        */
        function renderPrice(container){
            var priceObj = $("li[taskid]").find("span.sumOfMoney");
            $.each(priceObj,function(i){
                var price = $(this).html().replace('￥','');
                if(price!=''){
	                price = ecpUtils.formatNumber(price || 0, 2);
	                $(this).html('￥'+price);
                }
            })
        }
       
        /*
        *分别调用各业务组的扩展JS中callback方法.
        *@param isUntreated 是否待办
        */
        function invokeLazyload(isUntreated){
	          var taskMethod = 'lazyload';
	          var container; 
	          var data;
	          if(isUntreated){
		          	container=$("#tab_1",COMPONENT_CONTAINER);
		          	data=UNTREATED_TASK_LIST_CACHE;
	          }else{
		          	container=$("#tab_2",COMPONENT_CONTAINER);
		          	data=EXECUTED_TASK_LIST_CACHE;
	          }
	          //lazyLoad目前只有预算有
	          $.each(EXT_POINT_LIST_CACHE, function(typeName) {
	               var extPoint = EXT_POINT_LIST_CACHE[typeName];
	               if(extPoint){
		               var lazyLoadFunc = EXT_POINT_LIST_CACHE[typeName][taskMethod];
		               if (lazyLoadFunc) {
		                    //给流程扩展
		                   lazyLoadFunc(container,data,{"isUntreated":isUntreated});
		               }
	               }
	          });
        }
        
        /**
        *对每个分组最后一项增加css渲染.
         *@param container
         *            数据放置区
        */
        function addCss2LastTaskItem(container){
        	$("ul.listGroupContent",container.parent()).each(function(){
                $(this).find("li:last").addClass("solid");
            });
        }
        
        
        /* 激活任务按钮.
        *@param container 任务列表容器
        */
        function addZNTXFunc(container){
        		var serialid  ='0';
        		$("img[data-url]",container.parent()).dblclick(function(){
					var html = '<div class="colorModal modal  in ui-draggable" id="xzggModal'+serialid+'" tabindex="" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="z-index: 1049;">'+
				  	 '<div class="modal-dialog" style="width: 450px;">'+
					    '<div class="modal-content">'+
					      '<div class="modal-header" style="cursor: move;" >'+
					        '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
					        '<h4 class="modal-title" style="color: #4087c4;">'+i18n.newsCenter.title+'</h4>'+
					      '</div>'+
					      '<div class="modal-body">'+
					        '<div class="notice_details form-horizontal">'+
					          '<div class="row form-group">'+
					            '<label class="col-sm-2 control-label">'+i18n.newsCenter.sender+'</label>'+
					              '<div style="margin-top: 10px;" id="sender'+serialid+'" class="senderControlDiv">'+
					            '</div>'+
					           '</div>'+
					           '<div class="row form-group">'+
					            '<label class="col-sm-2 control-label">'+i18n.newsCenter.sendto+'</label>'+
					              '<div style="margin-top: -8px;" class="receiverControlDiv" id="receiverDiv'+serialid+'">'+
								  '</div>'+
					           '</div>'+
					        '<div class="row form-group">'+
						        '<label class="col-sm-2 control-label">'+i18n.newsCenter.content+'</label>'+
						        '<div class="" style="padding-top:10px">'+
							        '<textarea name="" id="content'+serialid+'" placeholder="'+i18n.newsCenter.inputContent+'" ng-placeholder="local.newsCenterDetail.inputContent" maxlength="500"  class="form-control" cols="50" rows="50" style="width: 355px;height:200px;resize:none;"></textarea>'+
							        '<div style="width:95%;text-align: right;color: rgb(175, 164, 164);"><span id="contentFontNum'+serialid+'">( <font>0</font>/500 )</span></div>'+
						        '</div>'+
						    '</div>'+
					      '</div>'+
					      '</div>'+
					      '<div class="modal-footer" >'+
					        '<button type="button" class="btn btn-primary" data-dismiss="modal" id="addZNTXNewsSure'+serialid+'" ng-bind="local.newsCenterDetail.addSure">提交</button>'+
					      '</div>'+
					   ' </div>'+
					  '</div>'+
					'</div>';
	        	    $(COMPONENT_CONTAINER).append(html);
	        	    
	        	    var taskId = $(this).parents("li[taskid]").attr("taskid");
					var username=$(this).attr('yhmc');
					var userid=$(this).attr('userid');
	        	    $("#xzggModal"+serialid,COMPONENT_CONTAINER).modal("show");
	    	    	limitZNTXContLength(serialid);
					sendZNTXMsg(serialid);
	    	        initZNTXData(userid,username,taskId,serialid);
           	});
        }
        
        /*
        *初始化站内通讯窗口数据.
        *@param userid 用户ID
        *@param username 接收人名称
        *@param taskId 任务id
        *@param serialid 序号
        */
        function initZNTXData(userid,username,taskId,serialid){
			$("#content"+serialid,COMPONENT_CONTAINER).val('');
	    	$("#sender"+serialid,COMPONENT_CONTAINER).html(ecpService.DataContextUtil.getUserName());
			var param = {};
			param.multiple=true;
			param.customOptions={};
			param.customOptions.rootOrg = ecpService.DataContextUtil.getCompidTop();
			param.customOptions.treeBZ = "1";
			param.winOption = {maxHeight:"350px"};
			$("#receiverDiv"+serialid,COMPONENT_CONTAINER).html('<select id="receiver'+serialid+'" style="width: 355px;" class="entitySelectPlace select2-default ecp-operator"></select>');
			$("#receiver"+serialid,COMPONENT_CONTAINER).ecpoperatorselect(param);
			if($.trim(username)!=''){
				$("#receiver"+serialid,COMPONENT_CONTAINER).comboBox(true).value([{"id":userid,"text":username}]);
		    }
        }
        
        /**
        *限制站内通讯内容长度.
        *@serialid 序号
        */
        function limitZNTXContLength(serialid){
        	//绑定内容记录已输入数字长度
			var $content = $("#content"+serialid,COMPONENT_CONTAINER);
			$content.off("keyup").on("keyup",function(){
				var val = $content.val();
				if(!val || val.length === 0){
					$("#contentFontNum"+serialid,COMPONENT_CONTAINER).find("font").text(0);
					return;
				}
				$("#contentFontNum"+serialid,COMPONENT_CONTAINER).find("font").text(val.length);
			})
        }
        
        /**
        *站内通讯,点击OK按钮.
        *@serialid 序号
        */
        function sendZNTXMsg(serialid){
           	$("#addZNTXNewsSure"+serialid,COMPONENT_CONTAINER).off("click").on("click",function(){
					var receiverComb = $("#receiver"+serialid,COMPONENT_CONTAINER).comboBox(true);
					if(!receiverComb){
						ecpUtils.notify(i18n.newsCenter.receiverEmpty);
						return;
					}
					var receivers = receiverComb.value();
					if(!receivers || receivers.length === 0){
						ecpUtils.notify(i18n.newsCenter.receiverEmpty);
						return;
					}
					var content = $("#content"+serialid,COMPONENT_CONTAINER).val();
					if(!content || content.length === 0){
						ecpUtils.notify(i18n.newsCenter.contentEmpty);
						$("#content"+serialid,COMPONENT_CONTAINER).focus();
						return;
					}
					var unitIds = [];
					for(var i=0,j=receivers.length; i<j; i++){
						var unit = receivers[i];
						if(unit){
							unitIds.push({"id":unit.id, "type":"USER", "name":unit.text});
						}
					}
					var subjectVal = content.substring(0,10);
					if(content.length>10){
						subjectVal+="...";
					}
					var vo = {
						"gid" : '',
						"messagetype" : "MESSAGE",
						"priority" : 1,
						"subject" : subjectVal,
						"content" : content,
						"sender" : ecpService.DataContextUtil.getUserId(),
						"iswithmail" : false,
						"iswithsms" : false,
						"receiver": $.toJSON(unitIds),
						"hasAttachment":false,
					};
					
					var beanId = 'com.ygsoft.ecp.component.message.service.context.IMessageContext';
					remoteService.doPostAsync(beanId,"sendMessage", [vo], function(res){
						if (res.isError()) {
							ecpUtils.notify(i18n.newsCenter.sendMsgFailed + res.data);
							return;
						}else{
							ecpUtils.notify(i18n.newsCenter.sendMsgSuccess);
						}
					});
			});
        }
        
        //固定待办调用方方法数组.
        var callerArr = [];
        
        //固定待办调用方数据存储数组.
        var callerDataArr = [];
        
        /**
        *更新待办总数.
        *@param addCount 增加待办总数数值
        */
        function updateUntreatedSize(addCount){
                var caller = arguments.callee.caller.name;
                if(callerArr.indexOf(caller)!=-1){
                    callerDataArr[callerArr.indexOf(caller)].total = addCount;
                }else{
                    var callerDataItem = {'obj':caller,'total':addCount};
                    callerArr.push(caller);
                    callerDataArr.push(callerDataItem);
                }
                var newCount = CURRENT_UNTREATED_QUERY_RES_SIZE * 1;
                $.each(callerDataArr,function(i,e){
                     newCount+=e.total*1;
                });
	        	$("#sumOfUnexecuted",COMPONENT_CONTAINER).html(newCount);
	        	//待固定待办总数统计出来后回调这个方法,再将刷新按钮重新启用
	        	$(".freshPage",COMPONENT_CONTAINER).removeAttr("disabled");
        }
        
        //是否由搜索框发起的搜索请求.
        var isQueryTriggerBySearch = false;
        
        /**
        *设置是否由搜索框发起的查询标志.
        */
        function setIsQueryTriggerBySearch(flag){
            isQueryTriggerBySearch = flag;
        }
        
        /**
        *如果查询结果只有一条，直接打开.
        */
        function openWhenOnlyOne(container){
            if(!isQueryTriggerBySearch){
               return;
            }
            isQueryTriggerBySearch=false;
            //搜索完后再打开
			var count = $("li[taskid]",COMPONENT_CONTAINER).length;
            if(count==1){
               $(".djInfor",COMPONENT_CONTAINER).trigger('click');
               $("#searchByTaskName",COMPONENT_CONTAINER).val("");
               var clearTextBtn = $("#clearTextBtn",COMPONENT_CONTAINER);
               clearTextBtn.addClass("hide").removeClass("btnClear"); // 添加隐藏标记
			}
        }
        
        /**
         * 激活任务按钮.
         *@param container 任务列表容器
         */
        function showAttachment(container) {
	           var params  =[];
	           var userId = CONF.context.loginContext.userId;
	   	   	   var compId = CONF.context.loginContext.loginOrgId;
	            $("li[taskid]",container.parent()).each(function(i){
	                   var taskId = $(this).attr("taskid");
	                   var taskVO = TASK_VO_LIST[taskId];
		               var param = {};
		               param.userId = userId;
		               param.compId= compId;
		               param.taskId = $(this).attr("taskid");
		               param.classId=taskVO.classId;
		               param.typeId=taskVO.typeId;
		               param.gid=taskVO.entityId;
		               params.push(param);
	            })
	          
				var beanId = "com.ygsoft.ecp.core.web.taskcenter.context.IQueryContext";
	            remoteService.doPostAsync(beanId,"getAttachmentInfos",[params], function(resp){
					if (resp.isSuccess()) {
						var resData = resp.data;
						var i,item,j = resData.length;
						for (i=0; i < j; i++) {
							item = resData[i];
							renderAttachmentInfo(container,item);
						}
					}
					if (resp.isError()) {
	                    ecpUtils.notify(resp.data);
	                }
				});
        }
        
    /**
	 * 渲染附件信息.
	 *@param container 
	 *@param item 
	 */
	function renderAttachmentInfo(container,obj) {
		if (!obj) return;
		var li = container.parent().find("li[taskid='" + obj.taskId + "']");
		if (!li.length) return;
		var taskName = li.find("span.djType");
		if (taskName&&obj.hasAttachment && obj.count) {
			//设置附件个数
			var attachmentDiv = li.find("div.djActions").find("div[tag=wfAttachment]");
			if(attachmentDiv.length==0){
			    var  attachmentHTML = "<a class=\"link_attachment\" title=\""+i18n.wfTodoAndDone.attachment+"\"><i class=\"icon_sm icon_attachment_blue\"></i>"+obj.count+"</a>";
			    if(taskName.parent('b.left').length>0){
			        $(attachmentHTML).insertAfter(taskName);
			    }else{
			   	 	var  newTaskNameHTML = "<b class='left'>" + taskName.prop('outerHTML') + attachmentHTML + "</b>";
					taskName.prop('outerHTML',newTaskNameHTML);
				}
				li.find("div.djActions").append("<div tag=\"wfAttachment\" class=\"wfHistory display-hide\" style=\"left:50%;right:auto\"><div class=\"arrow\"></div></div>");
			    li.data("attachmentData",obj.attachmentInfoList);
		    }
		}
	}
	
	/**
	 * 查看附件.
	 *@param resData
	 *@param el
	 */
	function viewAttachment(resData,el) {
	    el.closest("div.djList").find("div[tag='wfAttachment']").not(el).addClass("display-hide");
	    el.find("div.arrow").css({"left":"50%","right":"auto"})
		var viewed = el.attr("viewed");
		if (viewed == "1") {
			if (el.hasClass("display-hide")) {
				el.removeClass("display-hide");
			} else {
				el.addClass("display-hide");
			}
		} else {
			el.attr("viewed", "1");
			var userId = CONF.context.loginContext.userId;
	   	   	var compId = CONF.context.loginContext.loginOrgId;
	   	   	var data = resData.attachmentData;
	   	   	var attachList =[];
			for (var i=0, j = data.length; i < j; i++) {
				attachList.push(transFileVo(data[i]));
			}
			$.ecpAttachment(el,{data: attachList, loginContext:{userId : userId, compId : compId}});
			el.removeClass("display-hide");
			var btn = el.closest("li.taskItem").find("a.link_attachment");
			var pos = btn.position();
		    var top = pos.top + 35;
		    var width = el.closest("div.djList").find("div[tag='wfAttachment']").width();
		    var left;
		    if(pos.left-(width/2)>0){
		      left = pos.left-(width/2)- el.parent().parent().position().left;
		    }else{
		      left = pos.left- el.parent().parent().position().left;
		    }
			el.css({"top":top + "px","left": left + "px"});
		}
	}
	
	/**
	*转换附件参数为VO.
	*@param param 附件参数
	*@return 附件vo
	*/
	function transFileVo(param) {
		var file = {};
		file.gid = param.resId;
		file.fileLength = ecpUtils.formatNumber(param.fileLength/1024,2);
		file.smallPicUrl = param.smallPicUrl;
		file.previewUrl = param.resUrl;
		var name = param.fileAllName;
		if (name != null && name.indexOf(".") != -1) {
			var lastIndex = name.lastIndexOf(".");
			var fileName = name.substring(0, lastIndex);
			file.fileName = fileName;
		} else {
			file.fileName = name;
		}
		file.fileType = param.fileType;
		return file;
	}
        
        /**
         * button内容填充.
         */
        function drawTaskBtn() {
            $("button[taskType]",COMPONENT_CONTAINER).each(function() {
                var btnObj = $(this);
                //当前类型的所有按钮
                var btns = TASK_BTN_CACHE[btnObj.attr("taskType")];
                if (btns) {
                //当前按钮,名称即功能
                    var btnName = btnObj.attr("name");
                    //对已加急的按钮置灰
                    if(btnName=='hasten'){
                       var taskVO = TASK_VO_LIST[btnObj.parents("li[taskid]").attr("taskid")];
                       if(taskVO.isHastened==1){
                         $(this).addClass("disabled");
                         //IE10设为disabled后还可点击,为了兼容IE10,将taskType属性同时去除
                         $(this).removeAttr("taskType");
                       }
                    }
                    $.each(btns, function(i) {
                        if (btns[i].name == btnName) {btnObj.html("<i class=\""+ btns[i].cssClass + "\"></i>"+ btns[i].desc);}
                    });
                }
            });
        }
        
        /**
         * 激活任务按钮.
         *@param container 任务列表容器
         */
        function activeTaskBtn(container) {
            $("button[taskType]",container.parent()).bind('click',function() {
                var taskMethod = $(this).attr("name");
                var taskType = $(this).attr("taskType");
                if(taskType=='system'&&taskMethod=='repair'){
                	processRepair($(this).parents("li[taskid]").attr("processinstid"));
                }else{
	                var params = $(this).attr("params");
	                var mkjc = typeof($(this).attr('mkjc'))!='undefined'?$(this).attr('mkjc'):$(this).parents(".col-md-4").parent().find("div.djInfor").attr("mkjc");
	                var funcObj = getFuncObj(taskType, taskMethod);
	                if(!funcObj&&mkjc){
	                	funcObj = getMkFuncObj(mkjc,taskType,taskMethod);
	                }
	                var taskId = $(this).parents("li[taskid]").attr("taskid");
	                if (funcObj) {
	                    var taskVO = TASK_VO_LIST[$(this).closest("li").attr("taskid")];
	                    var btnObj = $(this);
	                    //发送催办SMS
	                    if(executeBtnList[0]=='hasten'&&taskMethod==executeBtnList[0]){
	                    	sendHastenSMS(taskId,funcObj,taskVO,btnObj);
	                    }else{
	                    	funcObj(taskVO, btnObj);
	                    }
	                    //点击后加急置灰
	                    if(taskMethod=='hasten'){
	                       $(this).addClass("disabled");
	                       //IE10设为disabled后还可点击,为了兼容IE10,将taskType属性同时去除
                           $(this).removeAttr("taskType");
	                    }
	                } else {
	                    ecpUtils.notify('不存在指定方法,方法名称为：' + taskMethod);
	                }
                }
           });
        }
        
        /**
        *调用流程自动修复接口.
        */
        function processRepair(processinstid){
            if(processinstid&&processinstid!=''){
	        	var params = [ecpService.DataContextUtil.getEcpDataContext(),processinstid,true,'任务中心调用流程修复接口'];
	        	var beanId = "com.ygsoft.ecp.core.workflow.service.internal.context.IWorkFlowRestoreContext";
	            remoteService.doPostAsync(beanId,"restore",params, function(resp){
					if (resp.isSuccess()) {
						var resData = resp.data;
						if(resData||resData=='true'){
							 ecpUtils.notify(i18n.wfTodoAndDone.repairSuccess);
						}else{
							 ecpUtils.notify(i18n.wfTodoAndDone.repairFail);
						}
					}
					if (resp.isError()) {
	                    ecpUtils.notify(resp.data);
	                }
				});
			}else{
				ecpUtils.notify(i18n.wfTodoAndDone.repairProcessinstidIsEmpty);
			}
        }
        
        /*
        *发送催办短信.
        *@param taskId 任务taskId
        *@param funcObj 方法对象
        *@param taskVO 任务VO
        *@param btnObj 任务按钮对象
        */
        function sendHastenSMS(taskId,funcObj,taskVO,btnObj){
				$dialog.dialog({
	                   title: i18n.newsCenter.info,
	                   content:i18n.newsCenter.smsConfirmMsg,
	                   isTip:true,
	                   showCloseButton:false,
	                   otherButtons:[i18n.newsCenter.no,i18n.newsCenter.yes],
	                   otherButtonStyles:['btn-link','btn-primary'],
	                   clickButton:function(sender, modal, index){
	                      if(index == 0){
	                        modal.modal("hide");
	                        funcObj(taskVO, btnObj);
	                      }
	                      if(index == 1){
							sendSMS(taskId,function(){modal.modal("hide");funcObj(taskVO, btnObj);});
	                      }
	                   }
	            });
        }
        
        /*
        *发送SMS.
        *@param taskId 当前任务taskId
        *@param callBak 回调函数
        */
        function sendSMS(taskId,callBak){
        	var beanId = 'com.ygsoft.ecp.core.web.taskcenter.context.ISMSMessageContext';
        	var dataContext = ecpService.DataContextUtil.newEcpDataContext();
        	var smsTxt = i18n.newsCenter.smsTxt;
            remoteService.doPostAsync(beanId,"send", [dataContext,taskId,smsTxt], function(res){
				if (res.isError()) {
				    if(res.data){
						ecpUtils.notify(i18n.newsCenter.sendSMSFailed+ i18n.newsCenter.dh + res.data + i18n.newsCenter.jh);
					}else{
						ecpUtils.notify(i18n.newsCenter.sendSMSFailed+ i18n.newsCenter.jh);
					}
				}else{
				    if(res.data.result){
						ecpUtils.notify(i18n.newsCenter.sendSMSSuccess);
					}else{
					    if(!res.data.errMsg){
					    	ecpUtils.notify(i18n.newsCenter.sendSMSFailed+ i18n.newsCenter.jh);
					    }else{
					    	ecpUtils.notify(i18n.newsCenter.sendSMSFailed+i18n.newsCenter.dh+ res.data.errMsg+i18n.newsCenter.jh);
					    }
					}
				}
				callBak();
			});
        }

		//单据任务中心扩展JS URL
		var GLOBAL_DJ_URL = '/grm/ecp/entity/scripts/taskcenter/com.ygsoft.ecp.taskcenter.entity.js';
		//流程任务中心扩展JS URL
		var GLOBAL_WF_URL = '/grm/core.workflow.engine/scripts/components/com.ygsoft.ecp.workflow.task.funcBtnExt.js';

        /**
         * 获取多个配置文件中taskType相同时,找第一个匹配的JS实现.
         *
         * @param taskType
         *            任务类型
         * @param taskMethod
         *            任务按钮指定的方法名称
         * @return 方法对象
         */
        function getFuncObj(taskType, taskMethod) {
            if(!taskMethod||taskMethod=='')return null;
		    var funcObj;
	   		//总是首先从流程先查找
	    	$.each(EXT_POINT_MK_CACHE,function(i){
					if(EXT_POINT_MK_CACHE[i].jsUrl==GLOBAL_DJ_URL||EXT_POINT_MK_CACHE[i].jsUrl==GLOBAL_WF_URL){
						if(EXT_POINT_MK_CACHE[i].extObj[taskMethod]){
							funcObj=EXT_POINT_MK_CACHE[i].extObj[taskMethod];
							return false;
						}
					}
			});
			return funcObj;
        }
        

        /**
         * 获取任务分组的html.
         *@param isUntreated 是否待办
         * @param data
         *            数据集
         * @return 任务分组的html
         */
        function getTaskGroupHTML(isUntreated,data) {
            var html = [];
            $.each(data, function(j, obj) {
                if(!obj.html){
	              	var json=parseTaskDetail(html,obj);
	                if (json && json.btnInfo) {
	                    var newBtnHtml=rebuildBtnHtmlWithSort(isUntreated,json.btnInfo,obj);
	                    html.push(getTaskHTML(obj, json.userInfo,json.bizInfo, json.seqInfo, newBtnHtml));
	                }
                }else{
                   html.push(obj.html);
                }
            });
            return html.join('');
        }
        
        
        /**
        *解析任务detail属性值.
        *@param htmlContainer 任务html容器
        *@param taskItem 任务项
        */
        function parseTaskDetail(htmlContainer,taskItem){
    	    if(!taskItem.detail||taskItem.detail==''){
    	    	if(window.console){
					window.console.log('detail属性值为空');
			    }
            }
            var detailJSON=null;
          	try{
        		detailJSON = $.parseJSON(taskItem.detail); 
            }catch(e){
            	if(window.console){
					window.console.log('detail属性值无法解析为json');
			    }
                htmlContainer.push(taskItem.detail);
            }
            return detailJSON;
        }
        
        /*
        *获取按钮对应的任务类型
        *@param btnHtml 按钮HTML
        *@return 任务类型
        */
        function getTaskType(btnHtml){
           if(btnHtml&&btnHtml!=''){
	           var pos = btnHtml.indexOf("taskType=\"");
	           return btnHtml.substr(pos+10,btnHtml.substr(pos+10).indexOf("\""));
           }
           return '';
        }
        
        /*
        *按事先约定的总按钮顺序进行按钮html重构.
        *@param isUntreated 是否待办
        *@param btnHtml 按钮HTML
        *@return 排序后的按钮HTML
        */
        function rebuildBtnHtmlWithSort(isUntreated,btnHtml,obj){
	        var taskType=getTaskType(btnHtml);
	        btnHtml = btnHtml.replaceAll("<div class=\"djActions\">","").replaceAll("</div>","");
	        var dataAttrArr = [];
	        getAttribute(btnHtml,dataAttrArr);
	        var newBtnHtml = "<div class=\"djActions\">";
	        var notExistsArr = [];
	        var existsArr = [];
	        if(isUntreated){
	        	 $.each(dataAttrArr,function(i){
	        	     if(untreatedBtnList.indexOf(dataAttrArr[i].name)!=-1){
	        	        existsArr.push(dataAttrArr[i]);
	        	     }else{
	        	        notExistsArr.push(dataAttrArr[i]);
	        	     }
	        	 });
	             $.each(untreatedBtnList,function(i){
	                 $.each(existsArr,function(j){
	                     if(untreatedBtnList[i]==existsArr[j].name){
	                     	newBtnHtml+="<button taskType=\""+existsArr[j].taskType+"\" name=\""+existsArr[j].name+"\" class=\""+existsArr[j].class+"\"><i class=\"icon_sm\"></i></button>";
	                     }
	                 });
	             });
	        }else{
	            $.each(dataAttrArr,function(i){
	               	 if(executeBtnList.indexOf(dataAttrArr[i].name)!=-1){
	               	     existsArr.push(dataAttrArr[i]);
	                 }else{
	        	         notExistsArr.push(dataAttrArr[i]);
	        	     }
	            });
	            $.each(executeBtnList,function(i){
	                 $.each(existsArr,function(j){
	                     if(executeBtnList[i]==existsArr[j].name){
	                     	//现金流量分类新增,暂时去掉撤回,回退按钮
	                        if(obj.paras&&obj.paras.indexOf('gris.mdm.fltx')!=-1&&executeBtnList[i]=='callback'){
		               	    	newBtnHtml+='';
		               	    //对于已办结的,由前端去掉
		               	 	}else  if(obj.taskStatus==TASK_CONST.TASK_STATUS.FINISH&&executeBtnList[i]=='hasten'){
		               	        newBtnHtml+='';
		               	    }else{
	                     		newBtnHtml+="<button taskType=\""+existsArr[j].taskType+"\" name=\""+existsArr[j].name+"\" class=\""+existsArr[j].class+"\"><i class=\"icon_sm\"></i></button>";
	                        }
	                     }
	                 });
	             });
	        }
	        $.each(notExistsArr,function(i){
	            newBtnHtml+="<button taskType=\""+notExistsArr[i].taskType+"\" name=\""+notExistsArr[i].name+"\" class=\""+notExistsArr[i].class+"\"><i class=\"icon_sm\"></i></button>";
	        });
	        newBtnHtml += "</div>";
	        return newBtnHtml;
        }

        /**
         * 获取任务项的概要html.
         *
         * @param date
         *            日期
         * @param groupName
         *            分组名称 上周/上月
         * @param count
         *            总数
         * @return 任务项的概要html
         */
        function getSummaryHTML(date, groupName, count) {
            var html = [];
            html.push("<ul class=\"listGroupTitle\">");
            html.push("<li><a class=\"lgt_collapse open\">");
            html.push("<i class=\"fa fa-caret-up\"></i></a></li>");
            html.push("<li><span class=\"caption\">$groupName</span></li>");
            if(date!=''){
            html.push("<li><span>$date</span><span>&nbsp;|&nbsp;</span>");
            }else{
             html.push("<li>");
            }
            html.push("<span>"+i18n.wfTodoAndDone.sum+"$count"+i18n.wfTodoAndDone.totalrow+"</span></li>");
            html.push("</ul>");
            var res = html.join('');
            res = res.replace('$date', date);
            res = res.replace('$groupName', groupName);
            return res.replace('$count', count);
        }

        /**
         * 获取任务项html(4种显示模型).
         *
         * @param taskItem
         *            任务条目 taskVO
         * @param userInfo
         *            用户信息
         * @param bizInfo
         *            业务信息
         * @param seqInfo
         *            排序信息
         * @param btnInfo
         *            按钮信息
         * @return 任务项html
         */
        function getTaskHTML(taskItem, userInfo, bizInfo, seqInfo, btnInfo) {
            var html = [];
            TASK_VO_LIST[taskItem.taskId] = taskItem;
            var processInstId = -1;
            if(taskItem.paras&&$.parseJSON(taskItem.paras)){
                processInstId = $.parseJSON(taskItem.paras).processInstId;
            }
            html.push("<li taskid=\"" + taskItem.taskId + "\" processinstid=\"" + processInstId + "\">");
            //只有待办需要显示加急与回退角标叠加效果
            if (taskItem.isBack==1&&taskItem.isHastened==1&&!taskItem.taskDealTime) {
            	html.push("<div class=\"marking htjj_marking\"></div>");
            // 回退
            }else if (!taskItem.taskDealTime&&taskItem.isBack==1) {
                html.push("<div class=\"marking ht_marking\"></div>");
            } else if (taskItem.isHastened==1) {
            	// 加急
                html.push("<div class=\"marking jj_marking\"></div>");
            } else {
                html.push("<div>");
            }
            
            html.push("<div class=\"row\">");
            html.push("<div class=\"col-md-6 col-sm-12\">$A$B</div>");
            html.push("<div class=\"col-md-2 col-sm-4\">$C</div>");
            html.push("<div class=\"col-md-4 col-sm-8\">$D</div>");
            html.push("</div>");
            html.push("</li>");
            // 增加停留时间表示
            if (!taskItem.taskDealTime) {
                bizInfo = addStayTimeStr(taskItem, bizInfo);
            }
            var res = html.join('');
            bizInfo = handleSpecialStr(bizInfo);
            userInfo = addDataUrlAttr(taskItem,userInfo);
            res = res.replace('$A', userInfo);
            res = res.replace('$B', bizInfo);
            res = res.replace('$C', seqInfo);
            res = res.replace('$D', btnInfo);
            return res;
        }
        
        /**
        *对摘要进行XSS攻击处理.
        *@param bizInfo 包含摘要的html
        *@return 对摘要进行XSS攻击处理后的html
        */
        function handleSpecialStr(bizInfo){
            if(bizInfo.indexOf('<p class="summary">')!=-1){
	        	var before = bizInfo.substring(0,bizInfo.indexOf('<p class="summary">')+'<p class="summary">'.length);
	            var after = bizInfo.substring(bizInfo.indexOf('<p class="summary">')+'<p class="summary">'.length);
	            var summary = after.substring(0,after.indexOf('</p>'));
	            summary = ecpUtils.escapeAngleBrackets(summary);
	            return before + summary + after.substring(after.indexOf('</p>'));
            }else{
            	return bizInfo;
            }
        }
        
        /**
        *增加头像src属性值
        *@param taskItem 任务条目
        *@param userInfo 用户信息
        *@return 用户信息
        */
        function addDataUrlAttr(taskItem,userInfo){
	            var yhmc='';
	            var userId;
	            var userName;
                if(taskItem.taskDealTime){
                	userId = taskItem.taskprocessorid;
                	userName = taskItem.taskprocessorname;
                }else{
                     //首环节
                     if(taskItem.pruserId==-1){
                     	 userId=USER_ID;
                     	 userName=ecpService.DataContextUtil.getUserName();
                     	 taskItem.yhxsmc=USER_DISPLAY_NAME;
                     }else{
	               		 userId = taskItem.pruserId;
	               		 userName = taskItem.prUserName;
               		 }
                }
            	if(userName){
        			yhmc = userName;
            	}
            	var searchKey  = "<p class=\"userName\">";
            	var pos = userInfo.indexOf(searchKey);
            	if(pos==-1){
            	   return userInfo;
            	}
            	var str = userInfo.substr(pos+searchKey.length);
            	var before = userInfo.substr(0,pos+searchKey.length);
            	var after = str.substr(str.indexOf("</p>"));
            	if(userId>=0&&!userName){
            		var after_before = after.substr(0,after.indexOf('<div class="infor"><p>')+'<div class="infor"><p>'.length);
            		var after_after = after.substr(after.indexOf('<div class="infor"><p>')+'<div class="infor"><p>'.length);
            		after = after_before + after_after.substr(after_after.indexOf("</p>"));
            	}
            	var newUserInfo;
            	if(taskItem.yhxsmc){
        			newUserInfo = before+taskItem.yhxsmc+after;
        		}else{
        			newUserInfo = before+after;
        		}
	            var beanId = 'com.ygsoft.ecp.app.mdm.service.xtyhxx.context.IEcpUserQueryContext';
	            var tokenId = ecpService.DataContextUtil.getTokenId();
	            var dataUrl = '/grm/ecp/webcore/FileAccessServlet?beanId='+beanId+'&method=findUserHeadPortrait&operParams=[null,'+userId+']&_token='+tokenId;
	            return newUserInfo.replaceAll("src=","yhmc='"+yhmc+"' userid='"+userId+"' data-url='"+dataUrl+"' src=");
        }
        
        /**
        *渲染用户个人头像.
        *@param container 任务列表容器
        */
        function renderUserphoto(container){
			var imgs = $(".listGroupContent",container.parent()).find("img[data-url]");
			var timeSerial = new Date().getTime();
			$.each(imgs, function() {
				var $this = $(this);
				var dataOriginal = $this.attr("data-url");
				if (!dataOriginal) {
					return true;
				}
				$this.attr("data-url", dataOriginal + "&tParam=" + timeSerial);
			});
			if(imgs && imgs.length !== 0){
				imgs.scrollLoading();
			}
		}
		
		var USERDETAIL_CACHE=[];
		
		/**
		*
		*激活鼠标停留事件显示用户详细信息功能.
		*@param container 任务列表容器
		*/
		function showUserDetail(container){
		    var imgs = $(".listGroupContent",container.parent()).find("img[data-url]");
			$.each(imgs, function() {
				var dataOriginal = $(this).attr("data-url");
				if (!dataOriginal) {
					return true;
				}
				$(this).on("mouseenter",function(e) {
				    var userId = $(this).attr("userId");
					if(!userId || userId == ""){return;}
				    var $me = $(this).parent();
					var $tel = $me.find("div.userInforBlock p.tel");
					if($tel && $tel.text()!= null && $tel.text()!= "" && $tel.text()!= "undefined"){
						return;
					}
					if($me.find("div.infor>p:eq(0)")&&$me.find("p.userName")){
						$me.find("div.infor>p:eq(0)").html($me.find("p.userName").html());
					}
					if(USERDETAIL_CACHE[userId]){
					 	setUserDetail($me,USERDETAIL_CACHE[userId]);
					}else{
						var beanId = "com.ygsoft.gris.authority.service.personinfo.context.IPersonInfoContext";
						var dataContext = ecpService.DataContextUtil.newEcpDataContext();
					    remoteService.doPostAsync(beanId, "getXtyhxxVO", [dataContext,userId], function(resp){
							if (resp.isSuccess()) {
								var res = resp.data;
								if(!res)return;
								USERDETAIL_CACHE[userId]={'movetel':res.movetel,'email':res.email};
								setUserDetail($me,USERDETAIL_CACHE[userId]);
							}
						});
					}
				});
			});
		}
		
		/**
		*设置用户详细信息.
		*@res  用户详细信息
		*/
		function setUserDetail(parentObj,res){
				var tel = res.movetel;
				if (!tel || tel =="null" || tel == "undefined") {
					tel = i18n.wfTodoAndDone.nophone;
				}
				parentObj.find("div.userInforBlock p.tel").html(tel);
				var email = res.email;
				if (!email || email =="null" || email == "undefined") {
					email = i18n.wfTodoAndDone.noemail;
				} 
				parentObj.find("div.userInforBlock p.email").html(email);
		}

        /**
         * 增加停留时间.
         *
         *@param obj 任务vo
         *@param bizInfo 原任务html
         *@return 增加停留时间后的任务html
         */
        function addStayTimeStr(obj, bizInfo) {
            //如果没有提单人信息,停留时间也无法填充
            var start = bizInfo.indexOf("<font class=\"tdsp\">");
            if (start != -1) {
				var str = '';
				if($(bizInfo).find(".tdsp").html()==''){
                    str = $(bizInfo).find(".tdsp").append(getTimeExpress(obj.stayTime));
				}else{
					str = $(bizInfo).find(".tdsp").append(i18n.wfTodoAndDone.bd).append(getTimeExpress(obj.stayTime));
				}
                var startContent = bizInfo.substr(0, start);
                var end = bizInfo.substr(start).indexOf("</font>");
                var endContent = bizInfo.substr(start).substr(end);
                return bizInfo = startContent + "<font class=\"tdsp\">" + str.html() + endContent;
            }else{
                if($("span.userName",$(bizInfo)).length>0&&$("span.userName",$(bizInfo)).html()!=''){
                	return bizInfo.substr(0,bizInfo.lastIndexOf("<p>")+3)+ i18n.wfTodoAndDone.bd + getTimeExpress(obj.stayTime).substr(1) + bizInfo.substr(bizInfo.lastIndexOf("</p>"));
                }else{
                	return bizInfo.substr(0,bizInfo.lastIndexOf("<p>")+3)+ getTimeExpress(obj.stayTime).substr(1) + bizInfo.substr(bizInfo.lastIndexOf("</p>"));
                }
            }
            return bizInfo;
        }

         /**
         *停留时长秒(单位秒)转化为分/时/天表示. 
         *@param time 延时时长,单位秒
         *@return 时间转字符串表示
         */
        function getTimeExpress(time) {
            var minute = 60;
            var hour = minute * 60;
            var day = hour * 24;
            var timeStr =i18n.wfTodoAndDone.staytime;
            
            if (time >= day) {//日期间隔超过1天,实际时间间隔也超过24小时
                timeStr +=  Math.round(time / day)  + i18n.wfTodoAndDone.day;
            } else if (time >= hour) {//日期间隔超过1天,但时间间隔不足24小时,按小时显示
            	timeStr += Math.round(time / hour) + i18n.wfTodoAndDone.hour;
            } else if (time >= minute) {
                timeStr += Math.round(time / minute) + i18n.wfTodoAndDone.minute;
            } else {
                timeStr += i18n.wfTodoAndDone.lessoneminute;
            }
            return timeStr;
        }

        /**
         * JS日期对象转换为xx年xx月xx日.
         *
         * @param date
         *            日期
         * @return 返回日期的'2016年6月15日'表示
         */
        function date2ChineseStr(date) {
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            return year + i18n.wfTodoAndDone.year + month + i18n.wfTodoAndDone.month + day + i18n.wfTodoAndDone.day_;
        }

        /**
         * 数字转星期几.
         *
         * @param num
         *            数字
         * @return 星期几
         */
        function number2WeekDay(num) {
            var weekDay = [ 
            i18n.wfTodoAndDone.sunday,
            i18n.wfTodoAndDone.monday,
            i18n.wfTodoAndDone.tuesday,
            i18n.wfTodoAndDone.wednesday,
            i18n.wfTodoAndDone.thursday,
            i18n.wfTodoAndDone.friday,
            i18n.wfTodoAndDone.saturday];
            return weekDay[num];
        }
        /**
         * 数据分类.
         */
        var TIME_CATEGORY = [ i18n.wfTodoAndDone.today, i18n.wfTodoAndDone.yesterday, i18n.wfTodoAndDone.lastweek, i18n.wfTodoAndDone.earlier ];

        /**
         * 输出所有任务html.
         *@param isUntreated 是否待办
         * @param container
         *            html放置区
         * @param data
         *            数据集
         */
        function outputHTML(isUntreated,container, data) {
            var html = [];
            $.each(data,function(i, obj) {
                    var summaryHTML = "";
                    var itemHTML = "";
                    var isFixTaskGroup = false;
                    if (obj && obj.length > 0) {
                        itemHTML = getTaskGroupHTML(isUntreated,data[i]);
                    }
                    if(itemHTML.indexOf("fixTask")!=-1){
                   	    isFixTaskGroup = true;
                   	}
                    var groupName='';
                    var chineseDay='';
                    if(i==-100){//更早
                        groupName = TIME_CATEGORY[3];
                    }else if(i==-99){//上周
                    	groupName = TIME_CATEGORY[2];
                    }else if(i==-98){//今天
                    	groupName = TIME_CATEGORY[0];
             			var currentDate = new Date(nowYear, nowMonth, nowDay);
                    	chineseDay=ecpUtils.formatDate(currentDate,null);
                    	 //今天
                    }else if(i==-97){//昨天
                    	groupName = TIME_CATEGORY[1];
                    	//昨天
            			var yesterdayDate = new Date(nowYear, nowMonth, nowDay - 1);
                    	chineseDay=ecpUtils.formatDate(yesterdayDate,null);
                    }else{
                        if(data[i]&&data[i].length>0&&data[i][0].taskCreateTime){
                        	var createTime = ecpUtils.strToDate(data[i][0].taskCreateTime, true, true,true);
                        	var createTimeDate = new Date(createTime.replace("-","/").replace("-","/"));
                        	groupName=number2WeekDay(createTimeDate.getDay());
	                        chineseDay=ecpUtils.formatDate(createTimeDate,null);
                        }
                    }
                    //如果分组元素都是特殊待办,分组的统计值应为0.
                    var count =0;
                    $.each(obj,function(i,e){
                       if(obj[i].html&&obj[i].html!=''){
                         count++;
                       }
                    });
                    if(!isFixTaskGroup){
	                    if(count==obj.length){
	                    	summaryHTML = getSummaryHTML(chineseDay,groupName,0);
	                    }else{
	                    	summaryHTML = getSummaryHTML(chineseDay,groupName,obj.length);
	                    }
                    }
                    html.push("<li class='taskItem'>");
                    html.push(summaryHTML);
                    //当前是固定待办分组则不显示分组栏
                   	html.push("<ul class=\"listGroupContent\">" + itemHTML + "</ul>");
                    html.push("</li>");
            });
            container.parent().find("li.taskItem").remove();    
            container.after(html.join(''));
        }
        
     /**
	 * 渲染核对审批列表  
	 *@param container html放置区
	 * @param {Array} data 要直接审批的数据
	 */
	function renderCheckAuditGrid(container,data){
	    var target = container.parents("#tabContent");
		initOption(data,target);
		//已存在表格实例则清除
		destroyJTable(target);
		initData(data,target);
		buildJTable(target);
		bindHeadChange(target);
		bindChange(target);
		renderJTable(target);
		//绑定打开批量审批页面
		bindClick(data,target);
	}
	
	/**
	*初始化批量审批的审批意见下拉选项.
	*@param target 批量审批表格所在容器对象
	*/
	function renderJTable(target){
		var $dtHeadCheck = $('#checkAuditGrid .group-checkable',target);
		//调整dataTables 搜索框的样式。
		$('#checkAuditGrid_wrapper .dataTables_filter input',target).addClass("form-control input-medium input-inline");
		$('#checkAuditGrid',target).removeClass("table");
		var parent = $dtHeadCheck[0].parentElement;
		if(parent) {
			var parentpareant = parent.parentElement;
			if(parentpareant && $(parentpareant).hasClass("checker")){
				$(parentpareant).removeClass("checker");
			}
		}
	}
	
	/**
	*初始化批量审批的审批意见下拉选项.
	*@param target 批量审批表格所在容器对象
	*/
	function destroyJTable(target){
		//已存在表格实例则清除
		if($.fn.dataTable.isDataTable("#checkAuditGrid")){
			var dtUI = $('#checkAuditGrid',target).dataTable();
			dtUI.fnDeleteRow();
			dtUI.fnDestroy();
			var checkboxex = $('#checkAuditGrid .group-checkable',target);
			if(checkboxex.is(":checked")){
				checkboxex.click();
			}
		}
	}
	
	/**
	*初始化批量审批的审批意见下拉选项.
	*@param data 批量审批数据
	*@param target 批量审批表格所在容器对象
	*/
	function initOption(data,target){
		var hdsplbModal = $("#hdsplbModal",target);
		// 审批意见
		var opt = {};
		opt.serialNo =  new Date().getTime();
		opt.initStr = i18n.wfTodoAndDone.agree;
		//下拉条宽度需修改
		opt.dropDownWidth = 870;
		auditOption.render($("#auditOption",hdsplbModal), opt);
		$(document).bind('click', function(e){
			e = e || window.event;
			var target = $(e.target);
			var $element = $("#auditOption",target).find('.dropdown-menu');
			if ($element.css('display') == 'none') {
				return;
			} else if (target.closest('.dropdown-menu').length == 0){
				$element.hide();
			}
			var txtValue = $("#post-dialog-notion",target).val();
			if (txtValue) {
				$("#opinionCaption",target).html(Math.round(wfUtils.countCharacters(txtValue)/2));
			}
		});
		
		var len = data.length;
		hdsplbModal.find("span.spdjzs").text(CURRENT_UNTREATED_QUERY_RES_SIZE);
		hdsplbModal.find("span.text-primary").text(len);
		hdsplbModal.find("span.jrspdjs").text(Math.abs(CURRENT_UNTREATED_QUERY_RES_SIZE-len));
	}
	
	/**
	*初始化JTable控件.
	*@param target 批量审批表格所在容器对象
	*/
	function buildJTable(target){
		//表格初始化
		$('#checkAuditGrid',target).dataTable({
				"aLengthMenu": [10, 25, 50, 100],
				"iDisplayLength": 10,
				"sPaginationType": "bootstrap",
				"aoColumnDefs": [
						{ 'bSortable': false, 'aTargets': [0] },
						{ "bSearchable": false, "aTargets": [0] },
						{"targets":[8],"visible":false,'render' : function(data, type, row) {
						    return row[8].replace(",","");
						}}
				],
				"sDom": '<"datatabletop"<"pull-left">f<"clearfix">>rt<"datatablebottom"<"pull-right"p><"pull-right"l><"pull-right"i><"clearfix">>',
				"oLanguage": {
					"sLengthMenu": i18n.wfTodoAndDone.pagedispaly+" _MENU_"+i18n.wfTodoAndDone.strip,
					"sZeroRecords": i18n.wfTodoAndDone.norecord,
					//"sProcessing": "&lt;img src='./loading.gif' /&gt;",
					"sInfo": i18n.wfTodoAndDone.dispaly+" _START_ - _END_ "+i18n.wfTodoAndDone.strip+"　"+i18n.wfTodoAndDone.total+" _TOTAL_ "+i18n.wfTodoAndDone.totalrow,
					"sInfoEmpty": i18n.wfTodoAndDone.norecords,
					"sInfoFiltered": i18n.wfTodoAndDone.from+"("+" _MAX_ "+i18n.wfTodoAndDone.filterrows+")",
					"sSearch": i18n.wfTodoAndDone.search+"：",
					"oPaginate": {
						"sFirst": i18n.wfTodoAndDone.fristpage,
						"sPrevious": i18n.wfTodoAndDone.prepage,
						"sNext": i18n.wfTodoAndDone.nextpage,
						"sLast": i18n.wfTodoAndDone.lastpage
					}
				}

		});
		//调整dataTables 每页展示记录数选择、分页的样式。
		$('#checkAuditGrid_wrapper .dataTables_length select',target).addClass("form-control input-xsmall");
	}
	
	/**
	*绑定批量审批复选框改变事件.
	*@param target 批量审批表格所在容器对象
	*/
	function bindHeadChange(target){
		//表头全选复选框绑定事件
		var $dtHeadCheck = $('#checkAuditGrid .group-checkable',target);
		$dtHeadCheck.parent().css("text-align","center");
		$dtHeadCheck.off("click").on("click",function(e){
			//阻止冒泡
			e.stopPropagation();
		});
		
		$dtHeadCheck.off("change").on("change",function () {
			var me = $(this);
			var set = me.attr("data-set");
			var checked = me.is(":checked");
			$(set).each(function () {
				var _$me = $(this);
				if (checked) {
					_$me.removeAttr("checked");
					_$me.click();
					_$me.attr("checked",true);
					_$me.parents('tr').addClass("active");
				} else {
					_$me.click();
					_$me.removeAttr("checked");
					_$me.parents('tr').removeClass("active");
				}                    
			});
		});
	}
	
	/**
	*绑定批量审批复选框改变事件.
	*@param target 批量审批表格所在容器对象
	*/
	function bindChange(target){
		//表头全选复选框绑定事件
		var $dtHeadCheck = $('#checkAuditGrid .group-checkable',target);
		$('#checkAuditGrid tbody',target).off("change").on("change",function(e){
			var me = $(e.target);
			if(me.hasClass("checkboxes")){
				if(me.is(":checked")){
					me.attr("checked",true);
					//勾选表头的全选复选框
					var allCk = $('#checkAuditGrid tbody input.checkboxes',target);
					var allCkFlag = true;
					for(var i = 0, j=allCk.length; i<j; i++){
						if(!$(allCk[i]).attr("checked")){
							allCkFlag = false; break;
						}
					}
					if(!$dtHeadCheck.is(":checked") && allCkFlag){
						$dtHeadCheck.click();
					}
				}else{
					me.removeAttr("checked");
					//去掉表头的全选复选框
					$dtHeadCheck.attr("checked",false);
				}
			}
		})
		
		$('#checkAuditGrid',target).off("change").on('change', 'tbody tr .checkboxes', function(){
				 $(this).parents('tr').toggleClass("active");
		});
		$('#checkAuditGrid tbody',target).off("click").on("click",function(e){
			//阻止点击冒泡
			e.stopPropagation();
		});
	}
	
	/**
	*绑定批量审批点击事件.
	*@param data 批量审批数据
	*@param target 批量审批表格所在容器对象
	*/
	function bindClick(data,target){
		//绑定打开批量审批页面
		$("#checkAudit",target).unbind("click").bind("click",function(){
			//批量审批
			//获得选中行数据
			var cks = $("#checkAuditGrid .checkboxes",target);
			var ckDatas = [];
			$.each(cks,function(){
				if($(this).attr("checked")){
					ckDatas.push($(this).attr("value"));
				}
			})
			if(ckDatas.length === 0){
				ecpUtils.notify(i18n.wfTodoAndDone.selecttoapprove);
				return;
			}
			var dataContainer = [];
			data.filter(function(n){
				for(var i=0,j=ckDatas.length; i<j; i++){
					if(n.taskId == ckDatas[i]){
						ckDatas = ckDatas.delByIndex(i);
						dataContainer.push(n);break;
					}
				}
			})
			if (dataContainer.length > 0) {
				var wfList=[];
				var optionButton = $("input[id^=post-dialog-notion]",target);
				var option = null;
				if(optionButton){
					option = optionButton.val();
				}
				for (var i=0, j=dataContainer.length; i < j; i++) {
					dataContainer[i].option = option;
					wfList.push(transferVO(dataContainer[i]));
				}
				bAudit.showDialog({billList:wfList,onClose:function(){
					auditOption.saveApprove();
					refreshPage();
				}});
			}
		});
	}
	
	/**
	*初始化批量审批表格数据.
	*@param data 批量审批数据
	*@param target 批量审批表格所在容器对象
	*/
	function initData(data,target){
	    var len = data.length;
		var tr='';
		var seq;
		var seqFormat;
		var summary;
		for(var i=0,j=len; i<j; i++){
		   var item = data[i];
		   seqFormat='';
		   seq='';
		   summary=''; 
		   if(item.seq!=-1){
		   		seqFormat = ecpUtils.formatNumber((item.seq ? item.seq : 0) || 0, 2);
		   		seq=item.seq;
		   }
		   if(item.desc){
			   summary=item.desc;
			   summary=summary.replace(i18n.wfTodoAndDone.replace_reason,'').replace(i18n.wfTodoAndDone.replace_summary,'');
		   }
			tr += '<tr><td class="alC" style="text-align: center;"><input type="checkbox" class="checkboxes" value="'+item.taskId+'"/></td>'+
				'<td class="alC">'+ (i+1) +'</td>'+
				'<td class="alC">'+ (item.taskCreateTime ? ecpUtils.strToDate(item.taskCreateTime, true, true,true).split(" ")[0] : "") +'</td>'+
				'<td class="alC">'+ (item.busno ? item.busno : "") +'</td>'+
				'<td class="alC">'+ (item.taskName ? item.taskName : "") +'</td>'+
				'<td class="alL" style="word-break:break-all;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;" title="'+summary+'">'+ summary +'</td>'+
				'<td class="alR" style="word-break:break-all">'+ seqFormat +'</td>'+
				'<td class="alC">'+ (item.prUserName ? item.prUserName : "") +'</td>'+
				'<td class="alR" style="word-break:break-all;display:none">'+ seq +'</td></tr>';
		}
		$("#checkAuditGrid",target).find("tbody").html(tr);
	}
	
	/**
	 * 转换待办VO.
	 * @param data 待办VO
	 */
	function transferVO(data) {
		var param = {};
		param.jcls = "com.ygsoft.ecp.component.portal.service.model.BsPortalWfInfoVO";
		param.workItemId = $.parseJSON(data.paras).workItemId;
		
		var processInstId_ = -1;
        if(data.paras&&$.parseJSON(data.paras)){
            processInstId_ = $.parseJSON(data.paras).processInstId;
        }
            
		param.processInstId = processInstId_;
            
		param.compId = ecpService.DataContextUtil.getLoginOrgId();
		param.userId = ecpService.DataContextUtil.getUserId();
		param.classId = $.parseJSON(data.paras).identifyEntity && $.parseJSON(data.paras).identifyEntity.classId;
		param.typeId = $.parseJSON(data.paras).identifyEntity && $.parseJSON(data.paras).identifyEntity.typeId;
		param.gid = $.parseJSON(data.paras).identifyEntity && $.parseJSON(data.paras).identifyEntity.gid;
		//预算控制总为true
		param.isBudget = true;
		param.processDefId = $.parseJSON(data.paras).processDefId;
		param.activityDefId = $.parseJSON(data.paras).activityDefId;
		param.activityInstId = $.parseJSON(data.paras).activityInstId;
		param.billId = data.busno;
		param.processChName = $.parseJSON(data.paras).processChName;
		param.postId = $.parseJSON(data.paras).postid;
		param.processDefName = $.parseJSON(data.paras).processDefName;
		param.needYsCheck = true;
		param.opinion = data.option;
		return param;
	}
	
    /*
	*获取查询参数.
	*@param isExecuted 是否已办
	*/
	function getQueryParams(isExecuted){
			var params = [{name:"USERID",value:USER_ID}];
            if(isExecuted){
	            var typeIdx = $("#sx_flowBtnGroup1 > button",COMPONENT_CONTAINER).index($("#sx_flowBtnGroup1 > button.active",COMPONENT_CONTAINER));
				var statusIdx = $("#sx_flowBtnGroup > button",COMPONENT_CONTAINER).index($("#sx_flowBtnGroup > button.active",COMPONENT_CONTAINER));
				//我经手的
				if(typeIdx==1){
			          addParam(params,{name : "EXCLUDE_TASKCREATOR",value : USER_ID});
				//我发起的
				}else if(typeIdx==0){
			          addParam(params,{name : "TASKCREATOR",value : USER_ID});
				}
				//流程进行中
				if(statusIdx==0){
				      addParam(params,{name : "EXCLUDE_TASKFINISH",value : TASK_CONST.TASK_STATUS.FINISH});
				//流程已完结
				}else if(statusIdx==1){
				      addParam(params,{name : "TASKSTATUS",value : TASK_CONST.TASK_STATUS.FINISH});
				}
			}
			var filterKey = $("#searchByTaskName",COMPONENT_CONTAINER).val().trim();
			var pattern = /.*_\d{4}_.*$/gi;
			if($.trim(filterKey)!=''){
			   //二维码
			   if(pattern.test(filterKey)){
			        filterKey = filterKey.substring(0,filterKey.indexOf("_"));
			    	addParam(params,{'name':'PZ','value':filterKey+'%'});
				}else if(filterKey.indexOf('ywdj.gris')!=-1){
			    	var value = ecpUtils.escapeAngleBrackets(filterKey);
			    	addParam(params,{'name':'DETAIL_','value':'%'+value+'%'});
				}else{
			    	var value = ecpUtils.escapeAngleBrackets(filterKey);
			    	addParam(params,{'name':'DETAIL','value':'%'+value+'%'});
				}
				setIsQueryTriggerBySearch(true);
			}
			if(isQueryTriggerBySearch){
			    if(filterKey!=''){
			    	addParam(params,{'name':'DO_FILTER','value':'true'});
			    }
			}
			return params;
	}
			
		/*更新查询参数(已存在将替换,不存在增加).
		*@param params原参数数组.
		*@param newParam 新参数
		*/
		function addParam(params,newParam){
		     var exists = false;
		     $.each(params,function(idx,obj){
				 if(obj.name==newParam.name){
			           obj.value = newParam.value;
			           exists = true;
			           return false;
				 }
			 });
			 if(!exists){
			    params.push(newParam);
			 }
		}
		
		var queryChanged = false;
		
		/**
		*查询维度是否已经改变.
		*/
		function isQueryChanged(flag){
			queryChanged=flag;
		}
			
        /**
         * 任务中心服务对象.
         */
        var service = {
            setIsQueryTriggerBySearch:setIsQueryTriggerBySearch,
            refreshUnTreatedTaskList:refreshUnTreatedTaskList,
            refreshExecutedTaskList:refreshExecutedTaskList,
            loadUnTreatedTaskList:loadUnTreatedTaskList,
            loadExecutedTaskList:loadExecutedTaskList,
            updateUntreatedSize:updateUntreatedSize,
            loadTaskExtList:loadTaskExtList,
            getQueryResSize:getQueryResSize,
            isQueryChanged:isQueryChanged,
            updateTaskRead:updateTaskRead,
            viewAttachment:viewAttachment,
            getQueryParams:getQueryParams,
            setInitParams:setInitParams,
            setTodoCount:setTodoCount,
            removeItem:removeTaskItem,
            setCurQuery:setCurQuery,
            refreshPage:refreshPage,
            taskConst:TASK_CONST,
            redoQuery:redoQuery
        };
        return service;
    });